package org.modelcc.io.java.checker;


import java.util.logging.Level;

import org.modelcc.io.java.JavaModelReader;
import org.modelcc.io.java.JavaModelChecker;
import org.modelcc.io.java.JavaLanguageMetadata;
import org.modelcc.io.java.JavaLanguageClass;
import org.modelcc.language.metamodel.MemberCollection;
import org.modelcc.language.metamodel.LanguageMember;

/**
 * Checks references
 */
public class ReferenceChecker extends JavaModelChecker<JavaLanguageMetadata> 
{	
	public ReferenceChecker (JavaModelReader reader)
	{
		super(reader);
	}
	
	@Override
	public void check(JavaLanguageMetadata metadata) 
	{
    	for (JavaLanguageClass e: metadata.getJavaElements()) {
    		JavaLanguageClass pe = (JavaLanguageClass) e;
    		for (int i = 0;i < pe.getMembers().size();i++) {
    			LanguageMember em = pe.getMember(i);
    			if (em.isReference()) {
    				JavaLanguageClass peref = (JavaLanguageClass) metadata.getClassElement(em.getElementClass());
    				if (peref.getKeyMembers().isEmpty()) {
    					if (!MemberCollection.class.isAssignableFrom(em.getClass())) {
    						pe.getMembers().set(i,new LanguageMember(em.getID(),em.getElementClass(),em.isOptional(),em.isKey(),false,em.getPrefix(),em.getSuffix(),em.getSeparator(),em.getEvaluator()));
    						log(Level.SEVERE, "In field \"{0}\" of class \"{1}\": This field is annotated with @Reference but its field class has no @ID members.", new Object[]{em.getID(), pe.getElementClass().getCanonicalName()});
    					} else {
    						MemberCollection mem = (MemberCollection)em;
    						pe.getMembers().set(i,new MemberCollection(em.getID(),em.getElementClass(),em.isOptional(),em.isKey(),false,em.getPrefix(),em.getSuffix(),em.getSeparator(),mem.getCollection(),mem.getMinimumMultiplicity(),mem.getMaximumMultiplicity(),em.getEvaluator()));
    						log(Level.SEVERE, "In field \"{0}\" of class \"{1}\": This field is annotated with @Reference but its field class has no @ID members.", new Object[]{em.getID(), pe.getElementClass().getCanonicalName()});
    					}
    				}
    			}
    		}
    	}
    }
}
